from flask import request, Response

from functools import wraps

from config import GlobalContextData

class OnlyDebugException(Exception):
    pass

def debug_only(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):

        if GlobalContextData.Debug:
            return f(*args, **kwargs)
        else:
            raise OnlyDebugException(f'只能在Debug环境访问相关资源: {request.path}')

    return decorated_function

def require_auth_static_user(username, password):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):

            def authenticate():
                """
                Sends a 401 response that enables basic auth.
                """
                return Response(
                    'Could not verify your access level for that URL.\n'
                    'You have to login with proper credentials.', 401,
                    {'WWW-Authenticate': 'Basic realm="Login Required"'})

            def check_auth(entered_username, entered_password):
                """
                Check if a username/password combination is valid.
                """
                return username == entered_username and password == entered_password

            auth = request.authorization
            if not auth or not check_auth(auth.username, auth.password):
                return authenticate()

            return f(*args, **kwargs)

        return decorated_function
    return decorator